import React, { useState, useEffect, useCallback } from "react";
import { TowerAPI } from "@/api/Towers";
import { ProjectAPI } from "@/api/project";
import { TensionSectionAPI } from "@/api/tensionSection";

import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { useToast } from "@/components/ui/use-toast";
import { Alert, AlertDescription } from "@/components/ui/alert";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Plus,
  Search,
  Trash2,
  Edit,
  MapPin,
  RefreshCw,
  AlertTriangle,
  MoreHorizontal,
  Info,
  ChevronLeft,
  ChevronRight,
} from "lucide-react";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import TowerForm from "../components/towers/TowerForm";

const towerTypeLabels = {
  tensionTower: "耐张塔",
  straightLineTower: "直线塔",
  angleTower: "转角塔",
  branchTower: "分支塔",
};

const typeColors = {
  tensionTower: "bg-purple-100 text-purple-800 border-purple-200",
  straightLineTower: "bg-green-100 text-green-800 border-green-200",
  angleTower: "bg-orange-100 text-orange-800 border-orange-200",
  branchTower: "bg-blue-100 text-blue-800 border-blue-200",
};

export default function Towers() {
  const [towers, setTowers] = useState([]);
  const [projects, setProjects] = useState([]);
  const [tensionSections, setTensionSections] = useState([]);
  const [filteredTowers, setFilteredTowers] = useState([]);
  const [selectedProjectId, setSelectedProjectId] = useState("all");
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedType, setSelectedType] = useState("all");
  const [showForm, setShowForm] = useState(false);
  const [editingTower, setEditingTower] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
  const { toast } = useToast();

  // 分页状态管理
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  const [paginatedTowers, setPaginatedTowers] = useState([]);

  const loadData = useCallback(async () => {
    setIsLoading(true);
    setError(null);
    try {
      const [towersData, projectsData, tensionSectionsData] = await Promise.all(
        [TowerAPI.getList(), ProjectAPI.getList(), TensionSectionAPI.getList()]
      );
      setTowers(Array.isArray(towersData.data) ? towersData.data : []);
      setProjects(Array.isArray(projectsData.data) ? projectsData.data : []);
      setTensionSections(
        Array.isArray(tensionSectionsData.data) ? tensionSectionsData.data : []
      );
    } catch (error) {
      console.error("加载数据失败:", error);
      setError("加载数据失败，请重试");
      toast({
        variant: "destructive",
        title: "加载失败",
        description: error.message || "无法加载杆塔数据",
      });
    } finally {
      setIsLoading(false);
    }
  }, [toast]);

  useEffect(() => {
    loadData();
  }, [loadData]);

  useEffect(() => {
    let filtered = towers;

    if (selectedProjectId !== "all") {
      filtered = filtered.filter((t) => t.projectId === selectedProjectId);
    }

    if (selectedType !== "all") {
      filtered = filtered.filter((t) => t.type === selectedType);
    }

    if (searchTerm) {
      filtered = filtered.filter(
        (t) =>
          t.towerNumber?.toLowerCase().includes(searchTerm.toLowerCase()) ||
          t.description?.toLowerCase().includes(searchTerm.toLowerCase())
      );
    }

    setFilteredTowers(filtered);
    // 重置分页到第一页
    setCurrentPage(1);
  }, [towers, selectedProjectId, selectedType, searchTerm]);

  // 处理分页逻辑
  useEffect(() => {
    const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    setPaginatedTowers(filteredTowers.slice(startIndex, endIndex));
  }, [filteredTowers, currentPage, itemsPerPage]);

  // 分页控制函数
  const handlePageChange = (pageNum) => {
    const totalPages = Math.ceil(filteredTowers.length / itemsPerPage);
    if (pageNum < 1 || pageNum > totalPages) return;
    setCurrentPage(pageNum);
  };

  const handleItemsPerPageChange = (count) => {
    setItemsPerPage(count);
    setCurrentPage(1); // 重置到第一页
  };

  // 渲染分页组件 - 修复显示问题
  const renderPagination = () => {
    // 确保在数据加载完成后才计算分页
    if (isLoading) return null;

    const totalItems = filteredTowers.length;
    const totalPages = Math.ceil(totalItems / itemsPerPage);

    // 即使只有一页也显示分页控件，方便用户调整每页显示数量
    return (
      <div className="flex flex-col sm:flex-row items-center justify-between gap-4 px-6 py-4 border-t border-gray-200 bg-white">
        <div className="text-sm text-gray-500">
          共 {totalItems} 条数据，显示
          {(currentPage - 1) * itemsPerPage + 1} 到
          {Math.min(currentPage * itemsPerPage, totalItems)} 条
        </div>
        <div className="flex items-center gap-2">
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="outline" size="sm" className="h-8">
                每页 {itemsPerPage} 条
                <MoreHorizontal className="ml-2 h-4 w-4" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              {[5, 10, 20, 50].map((count) => (
                <DropdownMenuItem
                  key={count}
                  onClick={() => handleItemsPerPageChange(count)}
                >
                  {count} 条/页
                </DropdownMenuItem>
              ))}
            </DropdownMenuContent>
          </DropdownMenu>
          <div className="flex items-center gap-1">
            <Button
              variant="outline"
              size="icon"
              className="h-8 w-8"
              onClick={() => handlePageChange(currentPage - 1)}
              disabled={currentPage === 1}
            >
              <ChevronLeft className="h-4 w-4" />
              <span className="sr-only">上一页</span>
            </Button>

            {/* 页码显示逻辑优化 */}
            {totalPages > 0 &&
              Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                let pageNum;
                if (totalPages <= 5) {
                  pageNum = i + 1;
                } else if (currentPage <= 3) {
                  pageNum = i + 1;
                } else if (currentPage >= totalPages - 2) {
                  pageNum = totalPages - 4 + i;
                } else {
                  pageNum = currentPage - 2 + i;
                }
                return (
                  <Button
                    key={pageNum}
                    variant={currentPage === pageNum ? "default" : "outline"}
                    size="icon"
                    className="h-8 w-8"
                    onClick={() => handlePageChange(pageNum)}
                  >
                    {pageNum}
                  </Button>
                );
              })}

            <Button
              variant="outline"
              size="icon"
              className="h-8 w-8"
              onClick={() => handlePageChange(currentPage + 1)}
              disabled={currentPage === totalPages || totalPages === 0}
            >
              <ChevronRight className="h-4 w-4" />
              <span className="sr-only">下一页</span>
            </Button>
          </div>
        </div>
      </div>
    );
  };

  const handleSubmit = async (towerData) => {
    try {
      if (editingTower) {
        await TowerAPI.update(editingTower.id, towerData);
        toast({ title: "更新成功", description: "杆塔信息已更新" });
      } else {
        await TowerAPI.create(towerData);
        toast({ title: "创建成功", description: "杆塔已创建" });
      }
      setShowForm(false);
      setEditingTower(null);
      loadData();
    } catch (error) {
      console.error("保存杆塔失败:", error);
      toast({
        variant: "destructive",
        title: "保存失败",
        description: error.message,
      });
    }
  };

  const handleEdit = (tower) => {
    setEditingTower(tower);
    setShowForm(true);
  };

  const handleDelete = async (towerId) => {
    if (!window.confirm("确定要删除此杆塔吗？此操作无法撤销。")) {
      return;
    }
    try {
      await TowerAPI.delete(towerId);
      toast({ title: "删除成功", description: "杆塔已删除" });
      loadData();
    } catch (error) {
      console.error("删除杆塔失败:", error);
      toast({
        variant: "destructive",
        title: "删除失败",
        description: error.message,
      });
    }
  };

  const handleCancel = () => {
    setShowForm(false);
    setEditingTower(null);
  };

  const getProjectName = (projectId) => {
    const project = projects.find((p) => p.id === projectId);
    return project ? project.projectName : "未知项目";
  };

  return (
    <div className="p-6 space-y-6 bg-gray-50 min-h-screen">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="flex flex-col lg:flex-row justify-between items-start lg:items-center gap-6 mb-8">
          <div>
            <h1 className="text-3xl font-bold text-gray-900 mb-2">杆塔管理</h1>
            <p className="text-gray-600">管理项目中的所有杆塔信息</p>
          </div>
          <div className="flex gap-3">
            <Button
              onClick={() => setShowForm(true)}
              className="bg-blue-600 hover:bg-blue-700"
            >
              <Plus className="w-4 h-4 mr-2" />
              新建杆塔
            </Button>
          </div>
        </div>

        {error && (
          <Alert variant="destructive" className="mb-6">
            <AlertTriangle className="h-4 w-4" />
            <AlertDescription className="flex items-center justify-between">
              <span>{error}</span>
              <Button variant="outline" size="sm" onClick={loadData}>
                <RefreshCw className="w-4 h-4 mr-1" />
                重试
              </Button>
            </AlertDescription>
          </Alert>
        )}

        {/* Filters */}
        <Card className="mb-6">
          <CardContent className="p-4 flex flex-col md:flex-row gap-4 items-center">
            <div className="relative flex-1 w-full md:w-auto">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
              <Input
                placeholder="搜索杆塔编号..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10"
              />
            </div>
            <Select
              value={selectedProjectId}
              onValueChange={setSelectedProjectId}
            >
              <SelectTrigger className="w-full md:w-48">
                <SelectValue placeholder="选择项目" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部项目</SelectItem>
                {projects.map((p) => (
                  <SelectItem key={p.id} value={p.id}>
                    {p.projectName}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Select value={selectedType} onValueChange={setSelectedType}>
              <SelectTrigger className="w-full md:w-36">
                <SelectValue placeholder="杆塔类型" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部类型</SelectItem>
                {Object.entries(towerTypeLabels).map(([key, label]) => (
                  <SelectItem key={key} value={key}>
                    {label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </CardContent>
        </Card>

        {/* Filter Guidance/Hint */}
        {(selectedProjectId !== "all" ||
          selectedType !== "all" ||
          searchTerm) && (
          <Alert className="mb-6 bg-blue-50 border-blue-200 text-blue-800">
            <Info className="h-4 w-4 text-blue-600" />
            <AlertDescription>
              当前显示的是已应用的筛选条件下的杆塔数据。
            </AlertDescription>
          </Alert>
        )}

        {/* Statistics - 使用filteredTowers */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
          <Card className="bg-gradient-to-r from-blue-50 to-blue-100 border-blue-200">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-blue-600">
                    {selectedProjectId !== "all" ||
                    selectedType !== "all" ||
                    searchTerm
                      ? "筛选结果"
                      : "总杆塔"}
                  </p>
                  <p className="text-2xl font-bold text-blue-700">
                    {filteredTowers.length}
                  </p>
                </div>
                <MapPin className="w-8 h-8 text-blue-500" />
              </div>
            </CardContent>
          </Card>
          <Card className="bg-gradient-to-r from-purple-50 to-purple-100 border-purple-200">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-purple-600">耐张塔</p>
                  <p className="text-2xl font-bold text-purple-700">
                    {
                      filteredTowers.filter((t) => t.type === "tensionTower")
                        .length
                    }
                  </p>
                </div>
                <Badge className="bg-purple-500" />
              </div>
            </CardContent>
          </Card>
          <Card className="bg-gradient-to-r from-green-50 to-green-100 border-green-200">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-green-600">直线塔</p>
                  <p className="text-2xl font-bold text-green-700">
                    {
                      filteredTowers.filter(
                        (t) => t.type === "straightLineTower"
                      ).length
                    }
                  </p>
                </div>
                <Badge className="bg-green-500" />
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Tower Form */}
        {showForm && (
          <TowerForm
            tower={editingTower}
            projects={projects}
            tensionSections={tensionSections}
            onSubmit={handleSubmit}
            onCancel={handleCancel}
          />
        )}

        {/* Towers Table */}
        <Card>
          <CardHeader>
            <CardTitle>杆塔列表 ({filteredTowers.length})</CardTitle>
          </CardHeader>
          <CardContent className="p-0">
            {isLoading ? (
              <div className="text-center py-12">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-4"></div>
                <p className="text-gray-500">加载中...</p>
              </div>
            ) : filteredTowers.length === 0 ? (
              <div className="text-center py-12">
                <MapPin className="w-16 h-16 text-gray-300 mx-auto mb-4" />
                <h3 className="text-lg font-semibold text-gray-900 mb-2">
                  暂无杆塔
                </h3>
                <p className="text-gray-500 mb-6">创建您的第一个杆塔</p>
                <Button
                  onClick={() => setShowForm(true)}
                  className="bg-blue-600 hover:bg-blue-700"
                >
                  <Plus className="w-4 h-4 mr-2" />
                  新建杆塔
                </Button>
              </div>
            ) : (
              <>
                <div className="overflow-x-auto">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>杆塔编号</TableHead>
                        <TableHead>类型</TableHead>
                        <TableHead>所属项目</TableHead>
                        <TableHead>高度(m)</TableHead>
                        <TableHead>呼称高(m)</TableHead>
                        <TableHead>杆塔绝缘子串长度 (m)</TableHead>
                        <TableHead>坐标</TableHead>
                        <TableHead className="text-right">操作</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {paginatedTowers.map((tower) => (
                        <TableRow key={tower.id} className="hover:bg-gray-50">
                          <TableCell
                            className="font-medium cursor-pointer"
                            onClick={() => handleEdit(tower)}
                          >
                            {tower.towerNumber}
                          </TableCell>
                          <TableCell>
                            <Badge
                              className={`${typeColors[tower.type]} border`}
                            >
                              {towerTypeLabels[tower.type]}
                            </Badge>
                          </TableCell>
                          <TableCell className="text-gray-600">
                            {getProjectName(tower.projectId)}
                          </TableCell>
                          <TableCell>
                            {tower.height
                              ? Number(tower.height).toFixed(0)
                              : "-"}
                          </TableCell>
                          <TableCell>
                            {tower.groundElevation
                              ? Number(tower.groundElevation).toFixed(0)
                              : "-"}
                          </TableCell>
                          <TableCell>
                            {tower.insulatorStringLength
                              ? Number(tower.insulatorStringLength).toFixed(0)
                              : "-"}
                          </TableCell>
                          <TableCell className="text-sm text-gray-500">
                            {tower.latitude && tower.longitude
                              ? `${Number(tower.latitude).toFixed(0)}, ${Number(
                                  tower.longitude
                                ).toFixed(0)}`
                              : "-"}
                          </TableCell>
                          <TableCell className="text-right">
                            <DropdownMenu>
                              <DropdownMenuTrigger asChild>
                                <Button variant="ghost" size="icon">
                                  <MoreHorizontal className="w-4 h-4" />
                                </Button>
                              </DropdownMenuTrigger>
                              <DropdownMenuContent align="end">
                                <DropdownMenuItem
                                  onClick={() => handleEdit(tower)}
                                >
                                  <Edit className="w-4 h-4 mr-2" />
                                  编辑
                                </DropdownMenuItem>
                                <DropdownMenuItem
                                  onClick={() => handleDelete(tower.id)}
                                  className="text-red-600"
                                >
                                  <Trash2 className="w-4 h-4 mr-2" />
                                  删除
                                </DropdownMenuItem>
                              </DropdownMenuContent>
                            </DropdownMenu>
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>
                {/* 确保分页始终显示（当有数据时） */}
                {renderPagination()}
              </>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
